package com.kosmos.dubhe.wxcp.provider;

import com.kosmos.dubhe.wxcp.config.WxCpConfiguration;
import com.kosmos.dubhe.wxcp.setting.WxcpTagScannerSetting;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpTag;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.NoSuchElementException;


/**
 * @author wukai
 */
@Component
@Data
@Slf4j
public class WxCpTagProvider {
    List<WxCpTag> tagList;
    private final WxcpTagScannerSetting setting;

    @PostConstruct
    public void init() {
        syncTag();
    }

    public String getTagCode(String tagName) {
        try {
            val tag = tagList.stream().filter(u -> tagName.equals(u.getName())).findFirst().orElseThrow(
                    () -> new RuntimeException(String.format(
                            "WxCpTagProvider getTagByName to query tagName:[%s] , tag not exist , ", tagName)));
            return tag.getId();
        } catch (NoSuchElementException e) {
            String message = String.format("WxCpTagProvider getTagCode to query tagName:[%s] , tag not exist , ", tagName);
            log.error(message);
            throw new NoSuchElementException(message);
        }
    }

    public void syncTag() {
        try {
            tagList = WxCpConfiguration.getCpService(setting.getAgentId())
                    .getTagService()
                    .listAll();
            log.debug("-------- syncTag --------");
            tagList.forEach(t -> log.debug("tag: [{}], name:[{}]", t.getId(), t.getName()));
        } catch (WxErrorException e) {
            log.error("TagProvider syncTag occur exception ", e);
        }
    }

}
